package com.didispace.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

/**
 * @author liangqq
 */
public class NotBreakerConfiguration {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }
    /**
     * 自定义错误
     */
    public class UserErrorDecoder implements ErrorDecoder {
        private Logger logger = LoggerFactory.getLogger(getClass());
        @Override
        public Exception decode(String methodKey, Response response) {
            Exception exception = null;
            try {
                //{"timestamp":"2019-06-19T12:22:48.301+0000","status":500,"error":"Internal Server Error","message":"业务异常！","path":"/throwsBizException"}
                String json = Util.toString(response.body().asReader());
                JSONObject jsonObject = JSON.parseObject(json);
                if(200 != jsonObject.getIntValue("status")){
                    // // 业务异常包装成 HystrixBadRequestException，不进入熔断逻辑
                    exception = new HystrixBadRequestException(jsonObject.getString("message"));
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            return exception;
        }
    }
}
